package com.etlmaster.executor.steps.sql;

import java.util.HashMap;
import java.util.Map;
import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.DpExecutorUtils;
import com.etlmaster.executor.utils.StepState;
import com.etlmaster.jdbc.JdbcTemplate;
/**
 * @author Wugf
 * @date 2016-03-08
 */
@StepInstruction("createIndex")
public class CreateIndexStep extends Step {

	private CreateIndexStepMeta meta;

	public CreateIndexStep(StepMeta meta) {
		super(meta);
		this.meta = (CreateIndexStepMeta) meta;
	}

	@Override
	protected int handle() {
		
		Map<String, Object> indexInfo = getIndexInfo(meta.getIndexName(), meta.getTableName());
		JdbcTemplate jdbc = new JdbcTemplate(meta.getDsName().toString());
		String createSql=getCreateIndexSql(indexInfo);
		if(createSql!=null&&createSql.length()>0)
		{
			try{
				jdbc.batchUpdate(createSql);
				return StepState.RUNNING_SUCCESSED;
			}catch(Exception e){
				meta.log("ERROR","创建index失败，异常信息为:{}",e.getMessage());
				return StepState.RUNNING_FAILED;
			}
		}else{
			meta.log("ERROR","非法语句：{}",createSql);
			return StepState.RUNNING_FAILED;
		}
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}

	private Map<String, Object> getIndexInfo(String indexName, String tableName) {
		String getIndexCfg = DataCollectionUtils.getProperties("selectIndex");
		JdbcTemplate jdbc = new JdbcTemplate();
		Map<String, Object> indexInfoMeta = jdbc.queryForMap(getIndexCfg);
		if (indexInfoMeta != null)
			return indexInfoMeta;
		else
			meta.log("WARN","没取到index {}信息，请检查配置", indexName);
		return null;
	}

	private String getCreateIndexSql(Map<String, Object> indexInfoMeta) {
		try {
			String getCreateIndexModel = DataCollectionUtils.getProperties("createIndex");
			Map<String, String> indexInfo = new HashMap<String, String>();
			indexInfo.put("indexName", indexInfoMeta.get("indexname").toString());
			indexInfo.put("tableName", indexInfoMeta.get("tabname").toString());
			indexInfo.put("colName", indexInfoMeta.get("indexcolumn").toString());
			indexInfo.put("keySize", indexInfoMeta.get("indexspace").toString());
			indexInfo.put("hashType", indexInfoMeta.get("indextype").toString());
			getCreateIndexModel = DpExecutorUtils.variableSubstitution(getCreateIndexModel, indexInfo);
			meta.log("INFO","index 语句为：{}",getCreateIndexModel);
			return getCreateIndexModel;
		} catch (Exception e) {
			meta.log("ERROR","获取index 创建语句失败，请检查配置.异常信息：{}",e.getMessage());
			return "";
		}
	}

}
